package com.bbz.core.nio.chapter1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoClient {
    private static final String host = "127.0.0.1";
    private static final int port = 1000;

    public static void start() throws Exception {
        //为进行事件处理分配了一个NioEventLoopGroup 实例，其中事件处理包括创建新的连接以及处理入站和出站数据
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //为初始化客户端，创建了一个Bootstrap 实例；
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    //为服务器连接创建了一个InetSocketAddress 实例；
                    .remoteAddress(new InetSocketAddress(host, port))
                    //当连接被建立时，一个EchoClientHandler 实例会被安装到（该Channel 的）ChannelPipeline 中；
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new EchoClientHandler());
                        }
                    });
            //调用Bootstrap.connect()方法连接到远程节点
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String args[]) {
        ExecutorService executor = Executors.newFixedThreadPool(500);
        try {
            for (int i = 0; i < 1000; i++) {
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            EchoClient.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            executor.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
